import Card from './components/card.jsx'
import BottomPanel from './components/bottom-panel.jsx'
import UserLayer from './components/user-layer.jsx'
import LeftPanel from './components/left-panel.jsx'
import UserGallery from './components/file-uploader.jsx'
import PhotoCropper from './components/photo-cropper.jsx'
import TopButtons from './components/top-buttons.jsx'
import Music from './components/music/index.jsx'
import TemplateMusic from './components/music/templateIndex.jsx'
import MapSetting from './components/map.jsx'
import Cover from './components/cover.jsx'
import AddPage from './components/add-page.jsx'
import { render } from 'react-dom'
import { connect, Provider } from 'react-redux'
import F, { compose } from 'lodash/fp'
import { store } from './store'
import React from 'react'
import { cropperReady } from './actions/content-change'
import { hashString, analysisSvg, hashCard } from "./utils"

render(
    <Provider store={store}>
        <LeftPanel />
    </Provider>
    , document.querySelector('.page-list-wp')
)

render(
    <Provider store={store}>
        <Card />
    </Provider>
    , document.querySelector('.edit-view')
)

render(
    <Provider store={store}>
        <UserGallery $modal={$('#change-editable-pic')} $cropper={$('#cut-img-modal')} />
    </Provider>
    , document.querySelector('.change-cover-upload-dialog')
)

render(
    <Provider store={store}>
        <PhotoCropper $modal={$('#cut-img-modal')} />
    </Provider>
    , document.querySelector('#cut-img-modal')
)

render(
    <Provider store={store}>
        <TopButtons />
    </Provider>
    , document.querySelector('#top-buttons')
)

if (window.MODE === 'template') {
    render(
        <Provider store={store}>
            <BottomPanel $gallery={$('#change-editable-pic')} />
        </Provider>
        , document.querySelector('.layer-wp')
    )
    render(
        <Provider store={store}>
            <Music />
        </Provider>
        , document.querySelector('#template-music-panel')
    )
} else {
    render(
        <Provider store={store}>
            <Music />
        </Provider>
        , document.querySelector('#edit-tab1')
    )

    render(
        <Provider store={store}>
            <UserLayer $gallery={$('#change-editable-pic')} />
        </Provider>
        , document.querySelector('.user-layer')
    )

    render(
        <Provider store={store}>
            <MapSetting />
        </Provider>
        , document.querySelector('#map-setting')
    )

    render(
        <Provider store={store}>
            <AddPage />
        </Provider>
        , document.querySelector('#add-page')
    )
}

$('#cut-img-modal').on('open.modal.amui', function () {
    store.dispatch(cropperReady(true))
});
$('#cut-img-modal').on('close.modal.amui', function () {
    store.dispatch(cropperReady(false))
});
$('#cover-modal').on('open.modal.amui', function () {
    store.dispatch(cropperReady(true))
});
$('#cover-modal').on('close.modal.amui', function () {
    store.dispatch(cropperReady(false))
});


const bootstrap = () => {
    store.dispatch({ type: 'FETCHED', pages: PAGES.pages, order: PAGES.order })
    store.dispatch({ type: 'SAVED_PAGES' })
    analysisSvg()
    $('#card img').attr('draggable', false)
    // return $.ajax({
    //     url: DATA_URL,
    //     dataType: 'json',
    //     success: _ => {
    //     },
    //     fail: _ => layer.alert('数据解析错误，请刷新重试！')
    // })
}

const _save = () => {
    let { card: { pages }, global: { map, cover }, music: { selected } } = store.getState()

    const pageToStr = F.compose(JSON.stringify, F.get('elements'))

    pages = pages.map(t => {
        let str = pageToStr(t)
        return { id: hashString(str), elements: str }
    })

    let submit = new FormData(document.getElementById('user-setting'))
    submit.append('pages', JSON.stringify(pages))
    submit.append('address', JSON.stringify(map))
    submit.append('song_id', selected ? selected.id || 0 : 0)
    submit.append('id', CARD_ID)
    submit.append('_token', UPLOAD_TOKEN)
    submit.append('user_cover', cover)

    return $.ajax({
        url: SAVE_URL,
        type: 'POST',
        processData: false,
        contentType: false,
        data: submit
    }).then(store.dispatch({ type: 'SAVED_PAGES' }))
}

const save = () => {
    _save()
        .then(res => layer.alert('保存成功'), res => layer.alert('保存失败'))
}


const isSaved = () => {
    let { global: { savedHash } } = store.getState()

    return savedHash === hashCard(store)
}

let exit = () => {
    const exitUrl = MODE == 'card' ? '/member/myTemplates' : '/manage/template/templateList'
    if (!isSaved()) {
        layer.confirm('你确认要退出吗？'
            , { icon: 3, title: '提示', btn: ['保存并退出', '直接退出'] }
            , index => _save().then(res => window.location.href = exitUrl)
            , () => window.location.href = exitUrl
        )
    } else {
        window.location.href = exitUrl
    }
}

//自动保存
setInterval(() => {
    isSaved() ? null : _save().then(res => layer.msg('修改已自动保存。'))
}, 3 * 1000 * 60)

window.store = store

window.bootstrap = bootstrap

window.save = save
window.exit = exit

window.hashCard = function () {
    return hashCard(store)
}
